package downloader

import com.google.common.net.InternetDomainName
import downloader.biquge.BiqugeDownloader
import downloader.bswx9.Bxwx9Downloader
import java.io.File
import java.net.URI
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.streams.toList

/**
 * Created by dm on 2017/8/24 0024.
 */
object Downloader {

    @JvmStatic
    fun main(args: Array<String>) {
        /*if (args.size < 2){
            println("url dir")
            System.exit(1)
        }*/
        val url = "https://www.xs.la/8_8881/"
        val dir = "e:\\TMP\\books"
        val domain = InternetDomainName.from(URI.create(url).host).topPrivateDomain().toString()
        val downloader:IDownloader = getDownLoader(url,domain)
        val name = downloader.getName()
        val bookDir = File(dir,name)
        if(!bookDir.exists()){
            bookDir.mkdirs()
        }
        downloader.download(bookDir)
        val l = Files.list(Paths.get(bookDir.toURI())).filter({it.fileName.toString().matches(Regex("[0-9]+"))}).sorted{ a, b ->
            val a1 = a.fileName.toString().toInt()
            val b1 = b.fileName.toString().toInt()
            a1.compareTo(b1)
        }.toList()
        val m = File(bookDir,"${name}.txt").outputStream()
        l.forEach {
            Files.copy(it,m)
        }
        m.close()
    }

    private fun getDownLoader(url: String, domain: String): IDownloader {
        if(domain == "biquge.com" ||
                domain == "biquge.com.tw"
                || domain == "xs.la"
                || domain == "biquzi.com")
            return BiqugeDownloader(url)
        if(domain == "bxwx9.org")
            return Bxwx9Downloader(url)
        throw IllegalArgumentException()
    }
}